"""
Case Type   : 资源池化
Case Name   : 备机注入dn故障，缩容备机
Create At   : 2024.10
Owner       : chen
Description :
    1.备二注入dn故障
    mv dn1 dn
    kill -9 pid(dn1)
    2.缩容备二
    gs_dropnode -U USER -G GROUP -h hostlist
    3.恢复故障
    mv dn dn1
    cm_ctl start -n 3
Expect      :
    1.成功
    2.合理报错
    3.恢复成功
"""

import os
import time
import unittest
from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Common import Common
from yat.test import Node
from yat.test import macro

class SharedStorage(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_comsh = CommonSH('PrimaryDbUser')
        self.com = Common()
        self.constant = Constant()
        self.pri_node = Node('PrimaryDbUser')
        self.sta2_node = Node('Standby2DbUser')
        self.db_host = self.sta2_node.db_host
        self.s_user = self.pri_node.ssh_user

    def test_shared_storage(self):
        text = f'''-----step1: 备二注入dn故障 expect: 成功-----'''
        self.log.info(text)
        pid = self.com.get_pid(self.sta2_node, 'bin/gaussdb')
        cmd = f'''mv {macro.DB_INSTANCE_PATH} {macro.DB_INSTANCE_PATH}_bak'''
        self.log.info(cmd)
        res = self.sta2_node.sh(cmd).result()
        self.log.info(res)
        cmd = f'''kill -9 {pid}'''
        self.log.info(cmd)
        res = self.sta2_node.sh(cmd).result()
        self.log.info(res)
        time.sleep(5)

        text = f'''-----step2: 缩容备二 expect: 合理报错-----'''
        self.log.info(text)
        cmd = f'''source {macro.DB_ENV_PATH};
        expect <<EOF
        set timeout 600
        spawn gs_dropnode -U {self.s_user} -G {self.s_user} \
            -h {self.db_host}
        expect "*drop the target node (yes/no)?*"
        send "yes\\n"
        expect eof\n''' + '''EOF'''
        self.log.info(cmd)
        res = self.pri_node.sh(cmd).result()
        self.log.info(res)
        self.assertIn('Failed to execute the command', res)

    def tearDown(self):
        text = f'''-----step3: 恢复故障 expect: 成功-----'''
        self.log.info(text)
        cmd = f'''mv {macro.DB_INSTANCE_PATH}_bak {macro.DB_INSTANCE_PATH}'''
        self.log.info(cmd)
        res = self.sta2_node.sh(cmd).result()
        self.log.info(res)
        res = self.pri_comsh.exec_cm_ctl('start -n 3')
        self.log.info(res)
        self.assertIn(self.constant.cm_start_node_success_msg, res)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')